const fs = require('fs');
const path = require('path');
const iconv = require('iconv-lite');
const imageExts = ['.jpg', '.png', '.gif', '.jpeg', '.mp3']; // 支持的文件扩展名


const WORDS_SHEET_PATH = 'words_sheet.csv';

// 从字符串中区分出名字和后缀
const splitNameExt = name => {
    const len = name.lastIndexOf('.')
    return {
        name: name.substr(0, len),
        ext: name.substr(len)
    }
}


///遍历所有图片后缀的文件夹
function traverseImages(dir, callback) {
    var files = fs.readdirSync(dir);
    files.forEach(file => {
        let fullPath = path.join(dir, file);
        var stats = fs.statSync(fullPath);
        if (stats.isFile() && imageExts.includes(path.extname(fullPath).toLowerCase())) {
            callback(fullPath, file); // 调用回调函数处理图片文件
        } else if (stats.isDirectory()) {
            traverseImages(fullPath, callback); // 递归遍历子目录
        }
    });
}


function isFileExists(filePath) {
    try {
        fs.accessSync(filePath);
        return true;
    } catch (error) {
        return false;
    }
}

var words_sheet = new Map();

function loadWordsSheet(dir) {
    if (!isFileExists(dir)) {
        return;
    }
    console.log("获取到翻译表文件");
    var textData = fs.readFileSync(dir, {
        encoding: "binary"
    });
    var buffer = Buffer.from(textData, "binary");
    var decodeData = iconv.decode(buffer, 'GBK');
    console.log("解析:", decodeData);
    // 假设有一个包含空格和换行符的字符串

    var lineWords = decodeData.split("\r\n");
    for (let i = 0; i < lineWords.length; i++) {
        var word = lineWords[i].split(",")[0];
        var wordEn = lineWords[i].split(",")[1];
        if (!words_sheet.has(word)) {
            console.log("已存在单词>>" + word);
            if (wordEn != null) {
                wordEn = wordEn.toLowerCase();
                wordEn = wordEn.replace(/\s+/g, '');
                // wordEn = wordEn.replace(" ", "_");
                // wordEn = wordEn.replace("\r\n", "_");
                // wordEn = wordEn.replace("\n", "_");
                words_sheet.set(word, wordEn);
            }
        }
    }
}

function saveWordsSheet(dir) {
    console.log(words_sheet.keys());
    var textData = "";
    words_sheet.forEach((v, k) => {
        if (k == null) return;
        textData += k + "," + v + "\r\n";
    });
    textData = iconv.encode(textData, 'GBK');
    fs.writeFileSync(dir, textData, "utf-8");
}

/**
 * 收集所有需要翻译的词语,并且在周围生成一个翻译对照表文件
 * @param {*} path 
 */
function collectWords(dir) {

    //读取文件，把之前收集过的单词，写入翻译映射表中，不会再次添加了
    var save_load_words_path = path.join(dir, "../", WORDS_SHEET_PATH);

    //先读取已经翻译过的表格数据
    loadWordsSheet(save_load_words_path);

    // 遍历所有图片
    traverseImages(dir, (imagePath, file) => {
        // console.log(splitNameExt(file)); // 处理每个图片文件
        let fullPath = path.join(dir, file);
        var stats = fs.statSync(fullPath);

        var obj = splitNameExt(file);
        var nameWorlds = obj.name.split(/ |_|\d|-/); //分割 空格或者下划线

        //进行分割后，过滤掉所有英文字符
        for (let i = 0; i < nameWorlds.length; i++) {
            const str = nameWorlds[i];

            //是中文的情况
            const regex = /[\u4e00-\u9fa5]+/g; //仅匹配中文字符，其他字符无视
            if (regex.test(str)) {
                if (!words_sheet.has(str)) {
                    words_sheet.set(str, str);
                    console.log("收集新单词>>" + str);
                }
                //记录单词，用于翻译
            }
        }
    });

    saveWordsSheet(save_load_words_path);

}

/**
 * 写入所有需要翻译的词语，对匹配的单词，进行替换
 * @param {*} path 
 */
function writeWords(dir) {
    //先读取已经翻译过的表格数据
    loadWordsSheet(path.join(dir, "../", WORDS_SHEET_PATH));

    // 遍历所有图片
    traverseImages(dir, (imagePath, file) => {
        // console.log(splitNameExt(file)); // 处理每个图片文件
        var obj = splitNameExt(file);
        var nameWorlds = obj.name.split(/( |_|\d|-)/); //分割 空格或者下划线
        //仅匹配中文字符，其他字符无视
        const regex = /[\u4e00-\u9fa5]+/g;
        var hasReplaceWords = false;
        for (let i = 0; i < nameWorlds.length; i++) {
            const str = nameWorlds[i];
            //如果含有中文字符，开始进行替换操作
            if (regex.test(str)) {
                if (words_sheet.has(str)) {
                    nameWorlds[i] = words_sheet.get(str);
                    hasReplaceWords = true;
                }
            }
        }

        //翻译后，重新拼接文件名，修改文件名
        var finalName = nameWorlds.join("") + obj.ext;
        var nextPath = path.join(dir, finalName);
        if (hasReplaceWords) {
            console.log("rename  " + imagePath + ">>" + nextPath);
            fs.renameSync(imagePath, nextPath);
        }
        //todo 
    });
}

// 获取命令行参数
const args = process.argv.slice(2); //第一个、第2个参数去掉，后面是自定义传入的参数

if (args[0] == null) {
    console.log("填写指令:");
    console.log("[c]ollect your/path   ->生成翻译表文件");
    console.log("[w]rite your/path   ->读取表格重命名文件名");
}

var inputPath = args[1];


switch (args[0]) {
    case "collect":
    case "c":
        collectWords(inputPath);
        break;
    case "write":
    case "w":
        writeWords(inputPath);
        break;
    default:
        break;
}